package com.zd.attgen;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.swing.filechooser.FileSystemView;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import com.zd.attgen.entity.Attendance;
import com.zd.attgen.service.ExcelService;
import com.zd.attgen.service.GeneratorService;
import com.zd.attgen.service.ProgressBar;

@SpringBootApplication
public class AttgenApplication {
	
	@Resource
	private GeneratorService generatorService;
	
	@Resource
	private ExcelService excelService;
	
	public static void main(String[] args) {
		ApplicationContext context = SpringApplication.run(AttgenApplication.class, args);
		AttgenApplication attApp = context.getBean(AttgenApplication.class);
		attApp.run();
	}
	
	public void run() {
		
		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/M/d");
		DateTimeFormatter df2 = DateTimeFormatter.ofPattern("yyyyMMdd");
		DateTimeFormatter tf = DateTimeFormatter.ofPattern("HH:mm");
		
		
		//考勤开始日期和结束日期
		LocalDate startLocalDate = LocalDate.now().plusMonths(-1).withDayOfMonth(26);
		LocalDate endLocalDate = LocalDate.now().withDayOfMonth(25);
		//设置每日考勤时间段
		LocalTime openLocalTime = LocalTime.parse("08:30", tf);
		LocalTime closeLocalTime = LocalTime.parse("17:30", tf);
		//假日、串休工作日
		List<LocalDate> holidayList = new ArrayList<>(0);
		List<LocalDate> workdayList = new ArrayList<>(0);
		//正常考勤人员
		List<String> attList;
		//长期出差人员
		List<String> btAttList;
		//长期请假人员
		List<String> leaveAttList;
		//哺乳假人员
		List<String> feedAttList;
		
		System.out.println();
		Scanner scanner = new Scanner(System.in);
		boolean ok = false;
		do {
			while(true) {
				System.out.print("输入考勤时间段("+ startLocalDate.format(df) + " " + endLocalDate.format(df) + "): ");
				try {
					String[] vals = scanner.nextLine().split(" +");
					if(vals[0].length() > 0) {
						startLocalDate = LocalDate.parse(vals[0], df);
						endLocalDate = LocalDate.parse(vals[1], df);
					}
					break;
				} catch (ArrayIndexOutOfBoundsException | DateTimeParseException e) {
					System.out.print("日期格式输入错误，重新输入。");
				}
			}
			System.out.print("考勤时间段为: " + startLocalDate.format(df) + " " + endLocalDate.format(df) + "是否正确(y/n)？");
			ok = !scanner.nextLine().equalsIgnoreCase("n");
		} while(!ok);
		System.out.println();
		do {
			while(true) {
				System.out.print("输入上下班时间("+ openLocalTime.format(tf) + " " + closeLocalTime.format(tf) + "): ");
				try {
					String[] vals = scanner.nextLine().split(" +");
					if(vals[0].length() > 0) {
						openLocalTime = LocalTime.parse(vals[0], tf);
						closeLocalTime = LocalTime.parse(vals[1], tf);
					}
					break;
				} catch (ArrayIndexOutOfBoundsException | DateTimeParseException e) {
					System.out.print("时间格式输入错误，重新输入。");
				}
			}
			System.out.print("上下班时间为: " + openLocalTime.format(tf) + " " + closeLocalTime.format(tf) + "是否正确(y/n)？");
			ok = !scanner.nextLine().equalsIgnoreCase("n");
		} while(!ok);
		System.out.println();
		ok = false;
		do {
			while(true) {
				System.out.print("输入假日(yyyy/M/d 空格间隔)，直接回车可跳过: ");
				try {
					String[] holidays = scanner.nextLine().split(" +");
					if(holidays[0].length() == 0) {
						ok = true;
						holidayList = new ArrayList<>(0);
						break;
					}
					holidayList = Arrays.stream(holidays).map( d -> {
						return LocalDate.parse(d, df);
					}).collect(Collectors.toList());
					break;
				} catch (ArrayIndexOutOfBoundsException | DateTimeParseException e) {
					System.out.print("日期格式输入错误，重新输入。");
				}
			}
			if(holidayList.size() > 0) {
				System.out.print("假日为:");
				holidayList.stream().forEach(d -> {
					System.out.print(d.format(df)+ " ");
				});
				System.out.print("是否正确(y/n)？");
				ok = !scanner.nextLine().equalsIgnoreCase("n");			
			}
		} while(!ok);
		System.out.println();
		ok = false;
		do {
			while(true) {
				System.out.print("输入串休工作日(yyyy/M/d 空格间隔)，直接回车可跳过: ");
				try {
					String[] workdays = scanner.nextLine().split(" +");
					if(workdays[0].length() == 0) {
						ok = true;
						workdayList = new ArrayList<>(0);
						break;
					}
					workdayList = Arrays.stream(workdays).map( d -> {
						return LocalDate.parse(d, df);
					}).collect(Collectors.toList());
					break;
				} catch (ArrayIndexOutOfBoundsException | DateTimeParseException e) {
					System.out.print("日期格式输入错误，重新输入。");
				}
			}
			if(workdayList.size() > 0) {
				System.out.print("串休工作日为:");
				workdayList.stream().forEach(d -> {
					System.out.print(d.format(df)+ " ");
				});
				System.out.print("是否正确(y/n)？");
				ok = !scanner.nextLine().equalsIgnoreCase("n");			
			}
		} while(!ok);
		System.out.println();
		ok = false;
		do {
			System.out.print("输入考勤人员 (空格间隔): ");
			String[] atts = scanner.nextLine().split(" +");
			attList = new ArrayList<>(0);
			if(atts[0].length() == 0) {
				System.out.print("考勤人员必须输入。");
			} else {
				attList = Arrays.asList(atts);
				System.out.print("考勤人员为: ");
				attList.stream().forEach(a -> System.out.print(a + " "));				
				System.out.print("是否正确(y/n)？");
				ok = !scanner.nextLine().equalsIgnoreCase("n");		
			}
		} while(!ok);
		System.out.println();
		ok = false;
		do {
			for (int i = 0; i < attList.size(); i++) {
				System.out.print("[" + i + "]" + attList.get(i));
			}			
			System.out.print("\n\n输入长期出差人员[序号](空格间隔)，直接回车可跳过: ");
			
			String[] indexs = scanner.nextLine().split(" +");
			btAttList = new ArrayList<>(0);
			if(indexs[0].length() == 0) {
				ok = true;
				btAttList = new ArrayList<>(0);
				break;
			}
			for (String index : indexs) {
				btAttList.add(attList.get(Integer.parseInt(index)));
			}				
			System.out.print("长期出差人员为: ");
			btAttList.stream().forEach(a -> System.out.print(a + " "));
			System.out.println();
			System.out.print("是否正确(y/n)？");
			ok = !scanner.nextLine().equalsIgnoreCase("n");		
		} while(!ok);
		System.out.println();
		ok = false;
		do {
			for (int i = 0; i < attList.size(); i++) {
				System.out.print("[" + i + "]" + attList.get(i));
			}			
			System.out.print("\n\n输入长期请假人员[序号](空格间隔)，直接回车可跳过: ");
			
			String[] indexs = scanner.nextLine().split(" +");
			leaveAttList = new ArrayList<>(0);
			if(indexs[0].length() == 0) {
				ok = true;
				leaveAttList = new ArrayList<>(0);
				break;
			}
			for (String index : indexs) {
				leaveAttList.add(attList.get(Integer.parseInt(index)));
			}				
			System.out.print("长期请假人员为: ");
			leaveAttList.stream().forEach(a -> System.out.print(a + " "));
			System.out.println();
			System.out.print("是否正确(y/n)？");
			ok = !scanner.nextLine().equalsIgnoreCase("n");		
		} while(!ok);
		System.out.println();
		ok = false;
		do {
			for (int i = 0; i < attList.size(); i++) {
				System.out.print("[" + i + "]" + attList.get(i));
			}			
			System.out.print("\n\n输入哺乳假人员(下班提前1小时)[序号](空格间隔)，直接回车可跳过: ");
			
			String[] indexs = scanner.nextLine().split(" +");
			feedAttList = new ArrayList<>(0);
			if(indexs[0].length() == 0) {
				ok = true;
				feedAttList = new ArrayList<>(0);
				break;
			}
			for (String index : indexs) {
				feedAttList.add(attList.get(Integer.parseInt(index)));
			}				
			System.out.print("哺乳假人员为: ");
			feedAttList.stream().forEach(a -> System.out.print(a + " "));
			System.out.println();
			System.out.print("是否正确(y/n)？");
			ok = !scanner.nextLine().equalsIgnoreCase("n");		
		} while(!ok);

		System.out.print("\n报表生成中");
		
		ProgressBar pb = new ProgressBar();
		pb.start();
		
		List<Attendance> attendances = generatorService.generate(startLocalDate, endLocalDate, openLocalTime, closeLocalTime,
				workdayList, holidayList, attList, btAttList, leaveAttList, feedAttList);

		String path = "沈阳考勤报表V" + startLocalDate.format(df2) + "-" + endLocalDate.format(df2) + ".xlsx";
//		path = AttgenApplication.class.getResource("/").getPath() + path;
		try {
			File file = new File(FileSystemView.getFileSystemView().getHomeDirectory(), path);
			OutputStream out = new FileOutputStream(file);
			excelService.export(attendances, out);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		pb.stop();
		System.out.println("\n报表生成成功，请在桌面上获取文件。");
		System.out.println("\nThank you for use, goodbye!");
		System.out.println("(Press enter key to exit.)");
		
		try {
			System.in.read();
		} catch (IOException e) {
			e.printStackTrace();
		}
		scanner.close();
	}

}
